//
//  ScanCodeViewController.m
//  LocomotiveGuards
//
//  Created by zwj on 15-11-23.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

#import "ScanCodeViewController.h"
#import "BrandViewController.h"
#import "QRCodeReaderViewController.h"
#import "PopLoadMsg.h"
#import "PopMsg.h"
@interface ScanCodeViewController () <UITextFieldDelegate,QRCodeReaderDelegate,UIAlertViewDelegate>
{
    UIButton *_btnLast;
    UIButton *_btnNext;
    UIButton *_scanBtn;
    UITextField *_fieldInput;
    NSString *_result;
}
@end

@implementation ScanCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addTitle:@"注册-车辆验证"];
    [self configView];
}

- (void)configView
{
    //车辆验证label
    UILabel *nameLabel = [self createLabelFrame:CGRectMake(30*W, 110*H, SCREEN_WIDTH-60*W, 30*H) title:@"车辆验证" font:[UIFont systemFontOfSize:26]];
    [self.view addSubview:nameLabel];
    
    //扫码框按钮
    _scanBtn = [self createBtnFrame:CGRectMake(50*W, CGRectGetMaxY(nameLabel.frame)+15*H, SCREEN_WIDTH-100*W, SCREEN_WIDTH-100*W) title:@"扫码框" bgImageName:@"13pic_scan" selectedImageName:@"13pic_scan" target:self action:@selector(scanAction:)];
    [_scanBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.view addSubview:_scanBtn];
    
    //手动输入框
    _fieldInput = [self createTextFieldFrame:CGRectMake(50*W, CGRectGetMaxY(_scanBtn.frame)+20*H, SCREEN_WIDTH-100*W, 35*H) title:nil placeholder:@"点击手动输入"];
    _fieldInput.returnKeyType = UIReturnKeyDone;
    _fieldInput.delegate = self;
    [self.view addSubview:_fieldInput];

    //上一步按钮
    _btnLast = [self addLastBtnTarget:self action:@selector(btnLastClicked:)];
    [self enableButton:_btnLast];
    
    //下一步按钮
    _btnNext = [self addNextBtnTarget:self action:@selector(btnNextClicked:)];
    [self disableButton:_btnNext];
}

#pragma mark - 网络请求
//验证SIM号请求
- (void)getSIMRequest
{
    PopLoadMsg *loadmsg = [PopLoadMsg new];
    [loadmsg delayLoadImages];

    
    
    
#warning  进行省市区三级联动修改测试
    
    
    
    NSString * phoneNumber = [[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNo"];
    
    
    
    NSDictionary *paramdic = @{@"loginId":phoneNumber,
                               @"imei":_fieldInput.text};
    NSString *url = [urlstring stringByAppendingString:@"verifyDevSimNum.do"];

    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success:^(AFHTTPRequestOperation *op,id responseObject){
        [loadmsg delayImagesRemove];
        NSDictionary *dic = (NSDictionary *)responseObject;
        NSLog(@"dic = %@", dic);
        
        NSInteger flag = [[dic objectForKey:@"flag"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        NSString *result = [dic objectForKey:@"simId"];
        if(flag == 0){
            //验证成功
            NSLog(@"result = %@", result);
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:result forKey:@"simId"];
            BrandViewController *brandVC = [BrandViewController new];
            [self.navigationController pushViewController:brandVC animated:YES];
        }
        else {
            [PopMsg showMessage:msg Lasttime:1.0f];
        }
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        [loadmsg delayImagesRemove];
        [PopMsg showMessage:@"网络异常，请重试" Lasttime:1.0f];
    }];
}

#pragma mark - 点击事件
//上一步，返回上一个界面
- (void)btnLastClicked:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

//下一步，执行SIM号验证请求
- (void)btnNextClicked:(id)sender
{
    if (_fieldInput.text.length == 14 || _fieldInput.text.length == 15) {
        [self getSIMRequest];
    }
    else {
        [PopMsg showMessage:@"imei码不正确" Lasttime:1.0f];
    }
}

//点击扫描按钮进行扫二维码
- (void)scanAction:(id)sender
{
    NSLog(@"二维码");
    static QRCodeReaderViewController *reader = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        reader                        = [QRCodeReaderViewController new];
        reader.modalPresentationStyle = UIModalPresentationFormSheet;
    });
    reader.delegate = self;
    
    [reader setCompletionWithBlock:^(NSString *resultAsString) {
        NSLog(@"Completion with result: %@", resultAsString);
    }];
    
    [self presentViewController:reader animated:YES completion:NULL];
}

//收起键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_fieldInput resignFirstResponder];
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSString *tempString = [_fieldInput.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([tempString isEqualToString:@""]) {
        [self disableButton:_btnNext];
    }
    else {
        [self enableButton:_btnNext];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_fieldInput resignFirstResponder];
    return YES;
}

#pragma mark - QRCodeReaderDelegate
- (void)reader:(QRCodeReaderViewController *)reader didScanResult:(NSString *)result withImage:(UIImage *)image
{
    [self dismissViewControllerAnimated:YES completion:^{
        NSLog(@"%@", result);
        _result = result;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"设备号:%@",_result] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
        [alert show];
    }];
}

- (void)readerDidCancel:(QRCodeReaderViewController *)reader
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        NSLog(@"cancel");
    }
    else if (buttonIndex == 1) {
        NSLog(@"confirm");
        _fieldInput.text = _result;
        [self enableButton:_btnNext];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
